﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using DiagramDesigner.BusinessModelObject;

namespace DiagramDesigner.Utils
{
    public static class Extensions

    {
        //public static MethodInfo GetGenericMethod(this Type t, string name, Type[] genericArgTypes, Type[] argTypes, Type returnType)
        //{
        //    var foo1 = (from m in t.GetMethods(BindingFlags.Public | BindingFlags.Static)
        //                where m.Name == name
        //                && m.GetGenericArguments().Length == genericArgTypes.Length
        //                && m.GetParameters().Select(pi => pi.ParameterType.IsGenericType ? pi.ParameterType.GetGenericTypeDefinition() : pi.ParameterType).SequenceEqual(argTypes) &&
        //                (returnType == null || (m.ReturnType.IsGenericType ? m.ReturnType.GetGenericTypeDefinition() : m.ReturnType) == returnType)
        //                select m).FirstOrDefault();

        //    return foo1 != null ? foo1.MakeGenericMethod(genericArgTypes) : null;
        //}
        public static T Parse<T>(this BaseField element,Type type)
        {
            try
            {
                return (T)Convert.ChangeType(element, type);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        public static bool IsInteger(string value)
        {
            try
            {
                Convert.ToInt32(value);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static T GetObject<T>(string className)
        {
            //Get the current assembly object
            var assembly = Assembly.GetExecutingAssembly();

            //Get the name of the assembly (this will include the public token and version number
            var assemblyName = assembly.GetName();

            //Use just the name concat to the class chosen to get the type of the object
            var t = assembly.GetType(assemblyName.Name + "." + className);

            //Create the object, cast it and return it to the caller
            return (T)Activator.CreateInstance(t);
        }

        public static T GetAttributes<T>(PropertyInfo p)
        {
            var attrs = p.GetCustomAttributes(typeof(T), true);
            if (attrs.Length > 0)
                return (T)attrs[0];

            return default(T);
        }

        public static string GetDescription(this Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());
            var attributes =
                  (DescriptionAttribute[])fi.GetCustomAttributes(
                  typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
    }
}
